<template>
  <div class="govern-container">
    <!-- <el-alert v-if="sourceData" style="background: #f4ddc3; color: #333" type="info" :closable="false" effect="dark">
      <div slot="title">
        风险: {{ sourceData.class }}-{{ sourceData.sourceLabel }}
        <a
          style="margin-left: 10px; color: #409eff !important; text-decoration: underline"
          target="_blank"
          :href="sourceData.solution"
          >治理方案请点击</a
        >
      </div>
    </el-alert> -->
    <alartInfo v-if="!isHideOptBtn" :data="detailData"></alartInfo>
    <div class="sec-title">
      风险主体
      <el-tooltip class="item" effect="dark" content="发现该风险的资产主体" placement="top">
        <el-button style="padding: 0" type="text" icon="el-icon-question"></el-button>
      </el-tooltip>
    </div>
    <sec-desc :column="3" colon :titleData="bodyInfoCol" :data="bodyInfoData" title=""></sec-desc>

    <sec-desc :column="3" colon :titleData="riskInfoCol" :data="riskInfoData" title="风险信息">
      <template v-slot:id>
        <el-link :underline="false" @click="goRiskCenterDetail">{{ riskInfoData["id"] }}</el-link>
      </template>
    </sec-desc>
    <el-collapse class="sec-collapse-suggest" v-model="activeNames">
      <el-collapse-item title="识别样例" :name="1">
        <div v-if="!['api-api-0:HTTP', 'selfexamination'].includes(source)">
          <!-- <div class="sec-title">识别样例</div> -->
          <!-- API禁采项 -->
          <sec-api-ana-samples
            :source="source"
            v-if="source.includes('api-api-1') || ['databaseAudit'].includes(source)"
            :data="analysisSamples.tableData"
            :columns="analysisSamples.tableCol"
          >
          </sec-api-ana-samples>

          <sec-table
            v-else
            style="margin-bottom: 20px"
            :tableData="analysisSamples.tableData"
            :tableCol="analysisSamples.tableCol"
          >
            <template v-slot:giftUrl="{ data }">
              <div v-html="data.row.giftUrl"></div>
            </template>
          </sec-table>
        </div>
      </el-collapse-item>
      <el-collapse-item title="处置建议" :name="2" v-if="ruleForm.disposalProposalEnable">
        <div>
          <!-- <div class="sec-title">处置建议</div> -->
          <div class="suggest" style="line-height: 25px" v-html="ruleForm.disposalProposalContent"></div>
        </div>
      </el-collapse-item>
    </el-collapse>
    <div class="ownerships">
      <div class="sec-title">风险信息</div>
      <sec-desc :border="false" :column="3" colon :data="ownershipInfoData" :titleData="ownershipInfoCol">
        <template v-slot:leader="{ data }">
          <dc-user :name="data.data.leader"></dc-user>
        </template>
      </sec-desc>
      <!-- <div style="margin-left: 10px"> -->
      <!-- <div class="sec-er-title">归属人</div>
        <sec-desc :border="false" :column="3" colon :data="assetOwnershipInfoData" :titleData="assetOwnershipInfoCol">
          <template v-slot:leader="{ data }">
            <dc-user :name="data.data.leader"></dc-user>
          </template>
        </sec-desc> -->
      <!-- <div class="sec-er-title">治理人</div> -->
      <!-- </div> -->
    </div>
    <div v-if="!isDetailPage">
      <div class="sec-title">{{ source == "selfexamination" ? "自查" : "治理" }}信息</div>
      <sec-form
        ref="secFormRef"
        :formData="formData"
        :span="8"
        :ruleForm="ruleForm"
        :rules="rules"
        :optionData="optionData"
        :hideProp="hideProp"
      ></sec-form>
      <div style="text-align: center">
        <el-button type="primary" :loading="isSaveLoading" icon="el-icon-document" @click="handleGovernSave"
          >保 存</el-button
        >
      </div>
    </div>
    <div v-else>
      <sec-desc
        v-if="isShowCustomInfo"
        title="治理流程"
        :column="3"
        :titleData="
          customInfoEnable
            ? customInfo.fields
            : source === 'gift'
            ? governGiftInfoTitleData
            : source == 'selfexamination'
            ? selfexaminationTitleData
            : governInfoTitleData
        "
        :border="false"
        :colon="true"
        :data="customInfoEnable ? customInfo.data : ruleForm"
      >
      </sec-desc>
    </div>
    <!-- <mysqlPwd v-if="['mysql-pwd'].includes(source)"></mysqlPwd> -->
    <!-- 治理流程图 -->
    <!-- v-if="detailData.appeal !== 2" -->
    <GovernIframe :data="detailData"></GovernIframe>
    <!-- 右侧多个操作按钮 -->
    <!-- <detail-operation v-if="!isHideOptBtn" :detailData="detailData"></detail-operation> -->
  </div>
</template>

<script>
import { getFeModelCfgList, getAnalysisSamplesApi } from "api/riskCenterApi";
import {
  saveGovernPlan,
  getOrderDetail,
  getGovernPlanNodeList,
  getMysqlBusiness,
  workDetailApi,
  getFeModelCfgStructApi,
} from "api/taskCenterApi";
import { getGovernBaseInfoApi, getCloseOrderInfo } from "api/taskCenterApi";

import GovernIframe from "./iframe";
import mysqlPwd from "./component/mysqlPwd.vue";
import detailOperation from "./component/detailOperation.vue";
import alartInfo from "./component/alertInfo";
import { helpConfigApi, getPermMenuApi } from "api/api";
export default {
  name: "govern",
  components: { GovernIframe, mysqlPwd, alartInfo, detailOperation },
  data() {
    return {
      activeNames: [], //1/2 识别样例、处置建议
      customInfoEnable: false,
      isShowCustomInfo: true,
      detailData: {}, //详情的基本数据
      sourceData: {},
      //查看抽屉展示的内容需要的数据
      apiTableData: [],

      analysisSamples: {
        tableData: [],
        tableCol: [
          { label: "类型", prop: "category" },
          { label: "样例（已脱敏）", prop: "samples" },
        ],
      },

      //主体信息
      bodyInfoCol: [],
      bodyInfoData: {},
      //权属信息
      // assetOwnershipInfoData: {},
      //治理人
      ownershipInfoData: {},
      ownershipInfoCol: [
        { type: "slot", label: "治理人", prop: "leader" },
        { label: "业务线", prop: "businessLineName" },
        { label: "部门", prop: "dept" },
        // { label: "一级部门", prop: "dept0" },
        // { label: "二级部门", prop: "dept1" },
        // { label: "三级部门", prop: "dept2" },
        // { label: "四级部门", prop: "dept3" },
      ],

      //风险信息
      riskInfoCol: [
        // { label: "风险ID", prop: "id" },
        // { label: "风险类型", prop: "riskType" },
        // { label: "风险分类", prop: "riskClass" },
        // { label: "风险暴露次数", prop: "nums" },
        // //todo
        // { label: "敏感信息类型", prop: "nums" },
        // { label: "识别来源", prop: "nums" },
      ],
      riskInfoData: {},

      isSaveLoading: false,
      governInfoTitleData: [{ label: "备注", prop: "remark" }],
      governGiftInfoTitleData: [
        { label: "治理方式", prop: "plan" },
        { label: "治理优先级", prop: "planLeval" },
        { label: "备注", prop: "remark", span: 3 },
      ],
      //自查信息
      selfexaminationTitleData: [
        {
          label: "API是否有敏感信息返回",
          prop: "piiFlag",
          formatter: (data) => {
            return this.formatText(data.piiFlag);
          },
        },
        {
          label: "API是否对公网开放",
          prop: "pnetworkFlag",
          formatter: (data) => {
            return this.formatText(data.pnetworkFlag);
          },
        },
        {
          label: "是否使用了共有读写的gift存储桶",
          prop: "pgiftFlag",
          formatter: (data) => {
            return this.formatText(data.pgiftFlag);
          },
        },
        { label: "桶名称", prop: "giftBucket" },
        {
          label: "API是否有鉴权",
          prop: "authFlag",
          formatter: (data) => {
            return this.formatText(data.authFlag);
          },
        },
        {
          label: "是否存在水平越权问题",
          prop: "hultraViresFlag",
          formatter: (data) => {
            return this.formatText(data.hultraViresFlag);
          },
        },
      ],
      //治理信息和自查信息
      formData: [
        { type: "select", label: "业务线", prop: "businessName", filterable: true },
        { type: "select", label: "治理方式", prop: "plan", filterable: true },
        { type: "select", label: "治理优先级", prop: "planLeval", filterable: true },
        { type: "textarea", label: "备注", prop: "remark", span: 24 },
      ],
      ruleForm: {
        businessName: "",
        plan: "",
        planLeval: "",
        remark: "",
      },
      optionData: {
        businessName: [],
        plan: [],
        planLeval: [
          { label: "P1", value: "P1" },
          { label: "P2", value: "P2" },
          { label: "P3", value: "P3" },
        ],
      },
      hideProp: {
        businessName: false,
      },
      rules: {
        plan: [{ required: true, message: "请选择", trigger: "change" }],
        businessName: [{ required: true, message: "请选择", trigger: "change" }],
      },
    };
  },
  computed: {
    type() {
      return this.$route.query.type;
    },
    source() {
      return this.$route.params.source;
    },
    processId() {
      return this.$route.query.processId;
    },
    uniqueId() {
      return this.$route.query.uniqueId;
    },
    isDetailPage() {
      return this.$route.query.isDetail;
    },
    isHideOptBtn() {
      return this.$route.query.hideOptBtn;
    },
  },
  created() {
    // helpConfigApi().then((res) => {
    //   let data = res.data[0];
    //   let config = JSON.parse(data.params.config);
    //   this.sourceData = config.find((item) => item.source === this.source) || "";
    // });
    this.initPage();
  },
  mounted() {
    this.hideProp.businessName = this.source === "gift" ? true : false;
    this.initOmegaTrack();
  },
  methods: {
    goRiskCenterDetail() {
      this.utils.$router(
        {
          path: `/govern/${this.type}/${this.source}`,
          query: { uniqueId: this.uniqueId },
        },
        "_blank",
      );
    },
    initOmegaTrack() {
      //来源 从page|dc|email
      let { from } = this.$route.query;
      this.status = this.$route.params.status;
      let statusLabel = { todo: "待认领", doing: "进行中", done: "已完成" };
      let status = this.status == "pending" ? "todo" : this.status;
      let fromEventId = `${status}_detail_sw`;
      let fromEventLabel = `工单中心-${statusLabel[status]}-详情`;
      this.utils.omegaTrackEvent(fromEventId, fromEventLabel, { from });
    },
    async initPage() {
      this.activeNames = [];
      let { data } = await workDetailApi({ processId: this.processId });
      let processData = await getCloseOrderInfo({ processId: data.processId });
      // console.log("[ processData ] >", processData);
      data.processData = processData.data;
      this.detailData = data;
      //待认领状态时 展开识别样例
      if (data.status == "pending" && !["0", "1"].includes(data.appeal)) {
        this.activeNames.push(1);
      }
      //待处理状态展示处置建议
      if (data.status == "doing" && !["0", "1"].includes(data.appeal)) {
        this.activeNames.push(2);
      }
      this.getGovernPlanNodeList(); //治理方式 下拉数据
      // this.getDataInfoTitle(); //主体信息表格头
      this.getMysqlBusiness(); //业务线 下拉数据
      this.getAnalysisSamples(); //识别样例
      this.getDetailInfo(); //详情的数据
      this.initGovernData(); //治理信息和自查信息数据
      this.getFeModelCfgStruct(); //获取风险信息和风险主体的表头信息
    },
    //获取风险信息和风险主体的表头信息
    getFeModelCfgStruct() {
      getFeModelCfgStructApi({ type: this.type, source: this.source, uniqueId: this.uniqueId, operateType: "1" }).then(
        async (res) => {
          console.log(res);
          let { dataInfoCol, riskInfoCol } = res.data;
          this.riskInfoCol = riskInfoCol.fields; //风险信息的表头
          this.bodyInfoCol = dataInfoCol.fields; //主题信息的表头
          let { data } = await getPermMenuApi();
          //说明有风险中心的权限
          let sign = data.some((item) => item.pid == 0 && item.remark === "风险中心");
          this.riskInfoCol.forEach((item) => {
            if (item.prop === "id" && sign) {
              // item["type"] = "slot";
              this.$set(item, "type", "slot");
            }
          });
          console.log("[ this.riskInfoCol ] >", this.riskInfoCol);
        },
      );
    },
    getDetailInfo() {
      const loading = this.openLoading();
      getGovernBaseInfoApi({ uniqueId: this.uniqueId, type: this.type, source: this.source }).then((res) => {
        console.log("[ res ] >", res);
        loading.close();
        const { dataInfo, assetOwnershipInfo, ownershipInfo, riskInfo } = res.data;
        this.bodyInfoData = dataInfo; //主体信息
        this.assetOwnershipInfoData = assetOwnershipInfo;
        this.ownershipInfoData = ownershipInfo;
        let { dept0, dept1, dept2, dept3 } = ownershipInfo;
        this.ownershipInfoData.dept = `${dept0} ${dept1 ? ">" : ""} ${dept1} ${dept2 ? ">" : ""} ${dept2}${
          dept3 ? ">" : ""
        } ${dept3}`;
        this.riskInfoData = riskInfo;
      });
    },
    formatText(data) {
      return data ? "是" : data == null ? "-" : "否";
    },
    getAnalysisSamples() {
      console.log("this.type", this.type);
      getAnalysisSamplesApi({
        type: this.type,
        source: this.source,
        uniqueId: this.uniqueId,
        processId: this.processId,
      }).then((res) => {
        let data = res.data;
        this.analysisSamples.tableData = data.list;
        data.columns.forEach((item) => {
          if (item.prop == "giftUrl") {
            item["type"] = "slot";
          }
        });
        this.analysisSamples.tableCol = data.columns;
      });
    },
    getMysqlBusiness() {
      getMysqlBusiness().then((res) => {
        this.optionData.businessName = res.data?.map((item) => ({ label: item, value: item }));
      });
    },
    // getDataInfoTitle() {
    //   //主体信息
    //   getFeModelCfgList({ type: this.type, source: this.source, operateType: "1" }).then((res) => {
    //     this.bodyInfoCol = res.data;
    //     console.log("[ this.bodyInfoCol ] >", this.bodyInfoCol);
    //   });
    // },
    initGovernData() {
      getOrderDetail({ processId: this.processId }).then((res) => {
        let data = res?.data;
        this.customInfoEnable = data.customInfoEnable;
        this.isShowCustomInfo = true; //默认是显示的
        if (data?.customInfoEnable) {
          this.customInfo = data.customInfo;
          this.isShowCustomInfo = data.customInfo.fields.length === 0 ? false : true;
          this.ruleForm = data;
          return;
        }
        if (data) {
          this.governInfoTitleData = data.remark ? [{ label: "备注", prop: "remark" }] : [];
          this.ruleForm = data;
        }
        //是否展示治理流程标题下的内容（包括标题 治理流程）
        //!this.detailData.showBpm &&
        if (
          !this.customInfoEnable &&
          this.source !== "selfexamination" &&
          !this.detailData.showGovernProcess &&
          this.governInfoTitleData.length === 0
        ) {
          this.isShowCustomInfo = false; //默认是显示的
        }
        // this.ruleForm.disposalProposalContent = `优先考虑不存储个人信息，特定必要情况需满足以下要求：<br/>1. 最小化权限设置，文档必须设置有限权限的访问，且确保人员、权限、可访问时间满足最小化原则，即当有特定需求时在有权限限制(区分查看、编辑、下载)的情况开放给少量特定人员，条件不满足时不再可访问/回收权限。<br/>2. 文档启用加密，涉及个人信息的文档应启用存储加密(申请地址：<a href="https://bpm.didichuxing.com/process/form/bykey/cooperqxsqlc?tenantId=Cooper">https://bpm.didichuxing.com/process/form/bykey/cooperqxsqlc?tenantId=Cooper</a>)。<br/>3. 及时清除数据，当需求已满足数据不再必要时，及时清除数据。
        // <a href="dchat://im/start_conversation?name=wlliweili_v">
        //   wlliweili_v
        //   <img src="/data/imgs/dc.png"/>
        // </a>`;
        // console.log("this.ruleForm", this.ruleForm);
      });
    },
    getGovernPlanNodeList() {
      getGovernPlanNodeList({ type: this.type, source: this.source }).then((res) => {
        this.optionData.plan = res.data || [];
      });
    },
    handleGovernSave() {
      if (this.$refs.secFormRef.submitForm()) {
        this.isSaveLoading = true;
        const params = {
          processId: this.processId,
          ...this.ruleForm,
        };
        saveGovernPlan(params).then(() => {
          this.isSaveLoading = false;
          this.message.success({ message: "保存成功" });
        });
      }
    },
  },
};
</script>

<style scoped lang="scss">
.sec-collapse-suggest {
  ::v-deep .el-collapse-item {
    position: relative;
    .el-collapse-item__arrow {
      position: absolute;
      left: 70px;
      top: 18px;
    }
  }
}
.suggest {
  ::v-deep img {
    width: 12px;
  }
}
.govern-container {
  padding: 10px 20px;
}
::v-deep #el-drawer__title {
  margin-bottom: 0;
}
.https-textarea {
  font-size: 15px;
}
.con {
  line-height: 25px;
  ul {
    margin: 0;
    li {
      list-style-type: circle;
    }
  }
  .con-text {
    text-indent: 2em;
  }
}
</style>
